# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :semaphore_test.py
# @Time      :2025/7/6 15:17
# @Author    :aiyimu

import threading
import time

semaphore = threading.Semaphore(3) # 最多允许3个线程同事访问

def access_resource(thread_id):
    print(f"线程{thread_id}尝试获取资源")
    with semaphore:
        print(f"线程{thread_id}获取到资源")
        time.sleep(2)
    print(f"线程{thread_id}释放资源")

threads = []
for i in range(5):
    t = threading.Thread(target=access_resource, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()